#!/usr/bin/env python
"""
创建示例产品数据
用于测试产品变体管理系统
"""

import os
import django

# 设置 Django 环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pecco_backend.settings')
django.setup()

from pecco_site.models import (
    Category, Product, ProductTranslation,
    ProductOption, ProductOptionValue, ProductOptionValueTranslation,
    ProductVariant, ProductVariantImage
)
from decimal import Decimal


def create_sample_product():
    """创建示例产品"""
    
    print("=" * 60)
    print("创建示例产品数据")
    print("=" * 60)
    
    # 1. 获取或创建分类
    print("\n1. 检查分类...")
    dog_category, created = Category.objects.get_or_create(
        slug='dog',
        defaults={
            'is_active': True,
            'sort_order': 1
        }
    )
    if created:
        print("   ✓ 创建 'dog' 分类")
        # 创建分类翻译
        from pecco_site.models import CategoryTranslation
        CategoryTranslation.objects.create(
            category=dog_category,
            locale='zh',
            name='狗狗',
            description='狗狗用品'
        )
        CategoryTranslation.objects.create(
            category=dog_category,
            locale='en',
            name='Dog',
            description='Dog products'
        )
    else:
        print("   ✓ 'dog' 分类已存在")
    
    # 2. 创建产品
    print("\n2. 创建产品...")
    product = Product.objects.create(
        is_active=True,
        sort_order=0,
        tag_new=True,
        tag_hot=False,
        tag_featured=False
    )
    product.categories.add(dog_category)
    print(f"   ✓ 创建产品 (ID: {product.id})")
    
    # 3. 创建产品翻译
    print("\n3. 创建产品翻译...")
    ProductTranslation.objects.create(
        product=product,
        locale='zh',
        name='舒适宠物床',
        short_desc='柔软舒适的宠物床，给您的爱宠一个温暖的家',
        rich_desc='<p>这是一款高品质的宠物床，采用优质材料制作，柔软舒适，透气性好。</p>',
        default_product_details='<ul><li>优质面料</li><li>柔软舒适</li><li>易于清洗</li></ul>',
        general_specifications='<p>材质：短毛绒<br>填充物：PP棉</p>'
    )
    ProductTranslation.objects.create(
        product=product,
        locale='en',
        name='Comfortable Pet Bed',
        short_desc='Soft and comfortable pet bed, a warm home for your pet',
        rich_desc='<p>This is a high-quality pet bed made of premium materials, soft and comfortable with good breathability.</p>',
        default_product_details='<ul><li>Premium fabric</li><li>Soft and comfortable</li><li>Easy to clean</li></ul>',
        general_specifications='<p>Material: Short plush<br>Filling: PP cotton</p>'
    )
    print("   ✓ 创建中文和英文翻译")
    
    # 4. 创建选项和选项值
    print("\n4. 创建选项和选项值...")
    
    # 规格选项
    size_option, _ = ProductOption.objects.get_or_create(
        name='size',
        defaults={
            'option_type': 'size',
            'is_active': True
        }
    )
    
    # 大号
    size_large, _ = ProductOptionValue.objects.get_or_create(
        option=size_option,
        value='Large',
        defaults={'is_active': True}
    )
    ProductOptionValueTranslation.objects.get_or_create(
        option_value=size_large,
        locale='zh',
        defaults={'value': '大号'}
    )
    ProductOptionValueTranslation.objects.get_or_create(
        option_value=size_large,
        locale='en',
        defaults={'value': 'Large'}
    )
    
    # 中号
    size_medium, _ = ProductOptionValue.objects.get_or_create(
        option=size_option,
        value='Medium',
        defaults={'is_active': True}
    )
    ProductOptionValueTranslation.objects.get_or_create(
        option_value=size_medium,
        locale='zh',
        defaults={'value': '中号'}
    )
    ProductOptionValueTranslation.objects.get_or_create(
        option_value=size_medium,
        locale='en',
        defaults={'value': 'Medium'}
    )
    
    # 颜色选项
    color_option, _ = ProductOption.objects.get_or_create(
        name='color',
        defaults={
            'option_type': 'color',
            'is_active': True
        }
    )
    
    # 红色
    color_red, _ = ProductOptionValue.objects.get_or_create(
        option=color_option,
        value='Red',
        defaults={
            'color_code': '#FF0000',
            'is_active': True
        }
    )
    ProductOptionValueTranslation.objects.get_or_create(
        option_value=color_red,
        locale='zh',
        defaults={'value': '红色'}
    )
    ProductOptionValueTranslation.objects.get_or_create(
        option_value=color_red,
        locale='en',
        defaults={'value': 'Red'}
    )
    
    # 蓝色
    color_blue, _ = ProductOptionValue.objects.get_or_create(
        option=color_option,
        value='Blue',
        defaults={
            'color_code': '#0000FF',
            'is_active': True
        }
    )
    ProductOptionValueTranslation.objects.get_or_create(
        option_value=color_blue,
        locale='zh',
        defaults={'value': '蓝色'}
    )
    ProductOptionValueTranslation.objects.get_or_create(
        option_value=color_blue,
        locale='en',
        defaults={'value': 'Blue'}
    )
    
    print("   ✓ 创建规格选项: 大号, 中号")
    print("   ✓ 创建颜色选项: 红色, 蓝色")
    
    # 5. 创建产品变体
    print("\n5. 创建产品变体...")
    
    variants_data = [
        {
            'options': [size_large, color_red],
            'sku': 'PB-L-RED',
            'price': Decimal('29.99'),
            'stock': 100,
            'details': '<p>大号红色宠物床，适合大型犬</p>'
        },
        {
            'options': [size_large, color_blue],
            'sku': 'PB-L-BLUE',
            'price': Decimal('29.99'),
            'stock': 50,
            'details': '<p>大号蓝色宠物床，适合大型犬</p>'
        },
        {
            'options': [size_medium, color_red],
            'sku': 'PB-M-RED',
            'price': Decimal('24.99'),
            'stock': 80,
            'details': '<p>中号红色宠物床，适合中型犬</p>'
        },
        {
            'options': [size_medium, color_blue],
            'sku': 'PB-M-BLUE',
            'price': Decimal('24.99'),
            'stock': 60,
            'details': '<p>中号蓝色宠物床，适合中型犬</p>'
        },
    ]
    
    for i, variant_data in enumerate(variants_data):
        variant = ProductVariant.objects.create(
            product=product,
            sku=variant_data['sku'],
            price=variant_data['price'],
            stock=variant_data['stock'],
            product_details=variant_data['details'],
            is_active=True,
            sort_order=i
        )
        variant.option_values.set(variant_data['options'])
        
        option_names = ' + '.join([str(opt) for opt in variant_data['options']])
        print(f"   ✓ 创建变体: {variant_data['sku']} ({option_names}) - ¥{variant_data['price']} - 库存: {variant_data['stock']}")
    
    print("\n" + "=" * 60)
    print("示例产品创建完成!")
    print("=" * 60)
    print(f"\n产品 ID: {product.id}")
    print(f"产品名称: {product.get_chinese_name()}")
    print(f"变体数量: {product.variants.count()}")
    print(f"\n访问商城查看: http://localhost:5174/products/{product.id}")
    print(f"访问后台编辑: http://localhost:5173/products-integrated/{product.id}/edit")
    print("")


if __name__ == '__main__':
    create_sample_product()

